import userApi from "../services/user";
import Taro from "@tarojs/taro";
import { setUserInfo } from "../utils/storage";
const namespace = "user";
const selectState = (state) => state[namespace];
let User = {
  namespace,

  state: {
    userId: "",
    name: "这是user的model",
    age: 1,
    loginFrom: {
      username: "",
      password: "",
    },
    userInfo: {},
  },
  reducers: {
    overrideStateProps(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    updateStateProps(state, { payload }) {
      const { name, value } = payload;
      return {
        ...state,
        ...{ [name]: { ...state[name], ...value } },
      };
    },
  },
  effects: {
    *Login(action, { call, put, select }) {
      const { loginFrom } = yield select(selectState);
      const params = { ...loginFrom };
      const res = yield call(userApi.login, params);
      console.log("res");

      if (res.code === 30000) {
        Taro.showToast({
          title: "登录成功",
          icon: "success",
        });
        yield setUserInfo(res?.data?.userInfo);
        Taro.switchTab({
          url: "../message/index",
        });
      } else {
        Taro.showToast({
          title: "登录失败",
          icon: "none",
        });
      }
      yield put({
        type: "resetLoginFrom",
      });
    },
    *getUserInfoById(action, { call, put, select }) {
      const { userId } = yield select(selectState);
      const params = { userId };
      const res = yield call(userApi.getUserInfoById, params);

      if (res.code === 30000) {
        yield put({
          type: "overrideStateProps",
          payload: {
            userInfo: res.data,
          },
        });
      }
    },

    *resetLoginFrom(action, { call, put, select }) {
      console.log(99);
      yield put({
        type: "overrideStateProps",
        payload: {
          loginFrom: {
            username: "",
            password: "",
          },
        },
      });
    },
  },
  subscriptions: {},
};
export default User;
